package com.example.tianling.baiduAi;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.concurrent.TimeUnit;

@Component
public class BaiduAi {
    public static final String API_KEY = "rQhcd7fMBqokdvDVrcG0HvGm";
    public static final String SECRET_KEY = "S4GbaiDDX8VBhkhVpPjQ0oRQ1cESdmFh";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    public String getBaiduAi(String content) throws IOException {



        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, content);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();

// 创建一个 OkHttpClient.Builder 对象
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();

// 设置连接超时时间（单位：毫秒）
        int connectTimeout = 100000; // 10秒
// 设置读取超时时间（单位：毫秒）
        int readTimeout = 100000; // 10秒

        httpClientBuilder.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS);
        httpClientBuilder.readTimeout(readTimeout, TimeUnit.MILLISECONDS);

// 使用 OkHttpClient.Builder 创建 OkHttpClient 对象
        OkHttpClient httpClient = httpClientBuilder.build();

        Response response = httpClient.newCall(request).execute();


        // Print the result value
//        System.out.println(response.body().string());
        JSONObject jsonObject = JSONObject.parseObject(response.body().string());
        String result = jsonObject.getString("result");
        return result;


    }


    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        JSONObject jsonObject = JSONObject.parseObject(response.body().string());
        String result = jsonObject.getString("access_token");
        return result;
    }

}